#include"tcp_client.h"
#include"Com_format.h"
#include "packag.h"
#include <QDebug>
//连接服务器
bool client_connect(QTcpSocket &sock,QString ip,int port)
{
    sock.connectToHost(ip,port);
    sock.waitForConnected(2000);
    return true;
}

//向服务器发送一个标识连接信号
bool first_signal(QTcpSocket &sock)
{
    char *cmd = new char[13];
    if(nullptr == cmd)
    {
        return false;
    }
    char *m = cmd;

    int top = COM_TOP;
    memcpy((void*)cmd,(void*)&top,4);
    cmd+=4;

    long long data_size = 0;
    memcpy((void*)cmd,(void*)&data_size,8);
    cmd += 8;

    char c = REQUST;
    memcpy((void*)cmd,(void*)&c,1);

    cmd = m;
    sock.write(cmd,13);
    delete []cmd;
    return true;
}

//发送函数
bool client_send(QTcpSocket &sock,const char *COM)
{
    if(nullptr == COM)
    {
        return false;
    }
    struct head data_head;
    unPackCmdData(data_head,COM);
    sock.write(COM,13+data_head.size);
    return true;
}

//接收数据
bool client_recv(QTcpSocket &sock,char *&COM,struct head &data_head)
{
    //读头数据
    QByteArray top = sock.read(13);
    struct head data_top;
    unPackCmdData(data_top,top);
    data_head = data_top;//返回数据类型
    //qDebug() << "数据类型是" << (int)data_top.cmd_type << "数据大小是" << (int)data_top.size;
    //如果是视频数据
    if(data_top.cmd_type == VIDEO)
    {
        int ret =0;
        int count = 0;
        char *buf = new char[data_top.size];
        while(data_top.size != count)
        {
            ret = sock.read(buf+count,data_top.size-count);
            if(ret < 0)
            {
                qDebug() << "读取错误";
                return false;
            }
            else if(ret == 0)
            {
                sock.waitForReadyRead(30000);
            }
            else
            {
                count += ret ;
            }
            //qDebug()<<"还需读取"<<data_head.size-count<<"已实际读取"<<count;
        }
        COM = new char[13+data_top.size];
        memcpy(COM,top,13);
        memcpy(COM+13,buf,data_top.size);
        delete []buf;
    }
    //如果是其他数据
    else
    {
        QByteArray buf = sock.read(data_top.size);
        COM = new char[data_top.size + 13];
        memcpy(COM,top,13);
        memcpy(COM+13,buf,data_top.size);
    }
    return true;
}
